package com.bdqn.springsecurity1.service;

import com.bdqn.springsecurity1.mapper.UserMapper;
import com.bdqn.springsecurity1.pojo.Menu;
import com.bdqn.springsecurity1.pojo.Role;
import com.bdqn.springsecurity1.pojo.TUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

@Service
public class UserService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库中查询用户
        TUser tUser = userMapper.findUserByName(username);
        if (tUser == null) {
            throw new UsernameNotFoundException("账号不存在");
        }
        //从数据库中查询到该角色的所有角色（含权限）
        tUser.setRoles(userMapper.findRolesByUserId(tUser.getUid()));
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        //取出用户的角色，封装到authorities中
        for (Role role : tUser.getRoles()) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
            //如果权限精确到权限菜单级别，则要补充这个
            for (Menu menu : role.getMenus()) {
                authorities.add(new SimpleGrantedAuthority(menu.getMenuname()));
            }
        }
        //下面的密码一般要加密
        return new User(tUser.getUsername(), new BCryptPasswordEncoder().encode(tUser.getPassword()), authorities);
    }
}
